Page({
  data: {
    searchKeyword: '',
    searchResults: [],
    hasSearched: false,
    tagList: ['年龄相仿', '兴趣相投', '性格温和', '有稳定工作', '热爱运动', '学历相当', '有责任心', '三观一致', '地域相近', '无不良嗜好','36D',
    '180cm',
    '有肌肉',
    '微胖',
    '18岁以上'],
    selectedTags: [],
    listData: [],
    current: 'someField', // 假设这里有一个默认的排序字段
    tagSelectedMap: {}
  },
  onInputChange(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },
  toggleTag(e) {
    const tag = e.currentTarget.dataset.tag;
    const selectedTags = this.data.selectedTags;
    const index = selectedTags.indexOf(tag);
    if (index > -1) {
      selectedTags.splice(index, 1);
    } else {
      selectedTags.push(tag);
    }
    this.setData({
      selectedTags: selectedTags
    });
    this.updateTagSelectedMap();
    // 点击标签后触发搜索
    this.onSearch();
  },
  onSearch() {
    const keyword = this.data.searchKeyword;
    const selectedTags = this.data.selectedTags;
    const users = this.data.listData; // 使用从数据库获取的数据
    let searchResults = [];
    users.forEach(user => {
      const standards = user.standard.split(',');
      const matchKeyword = keyword === '' || standards.some(standard => standard.includes(keyword));
      const matchTags = selectedTags.length === 0 || selectedTags.some(tag => standards.includes(tag));
      if (matchKeyword && matchTags) {
        searchResults.push({
          _id: user._id,
          userPhoto: user.userPhoto,
          nickName: user.nickName,
          standard: user.standard
        });
      }
    });
    this.setData({
      searchResults: searchResults,
      hasSearched: true
    });
  },
  getListData() {
    const db = wx.cloud.database();
    db.collection('users').field({
      _id: true,
      userPhoto: true,
      nickName: true,
      links: true,
      standard: true // 确保获取到 standard 字段
    })
   .orderBy(this.data.current, 'desc')
   .get().then((res) => {
      console.log(res);
      this.setData({
        listData: res.data
      });
      this.updateTagSelectedMap();
    });
  },
  updateTagSelectedMap() {
    const map = {};
    this.data.tagList.forEach(tag => {
      map[tag] = this.data.selectedTags.includes(tag);
    });
    this.setData({
      tagSelectedMap: map
    });
  },
  onLoad() {
    this.getListData(); // 在页面加载时获取数据
  }
});    